import { Col, Row, Spin, Icon } from "antd";
import { Card, ListView, Tabs, WhiteSpace, Modal } from "antd-mobile";
import moment from "moment";
import { addon } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import { request, setMainFormTitle, setMainFormBack } from "src/business/util_tool";
import { AppServiceUtility } from "src/projects/app/appService";
import { ROUTE_PATH } from "src/projects/app/util-tool";
import '../../buss-pub/news-list/index.less';
import { getGoodLookTimeShow } from "../activity-manage";

function MyBody(props: any) {
    return (
        <div className="am-list-body my-body" style={{ height: '100%' }}>
            {props.children}
        </div>
    );
}

const alert = Modal.alert;
/**
 * 组件：我的发布列表视图控件状态
 */
export interface MyReleaseViewState extends ReactViewState {
    /** 长列表数据 */
    dataSource?: any;
    /** 请求的数据 */
    list?: any[];
    /** 上拉加载 */
    upLoading?: boolean;
    /** 下拉刷新 */
    pullLoading?: boolean;
    /** 长列表容器高度 */
    height?: any;
    /** 当前第几页 */
    page: number;
    /** 记录tab状态 */
    tab_status?: string;

    defaultImg?: string;

    tabs: any;

    empty?: any;
    animating?: any;
    pageCount?: number;
}
/**
 * 组件：我的发布列表视图控件
 */
export class MyReleaseView extends ReactView<MyReleaseViewControl, MyReleaseViewState> {
    constructor(props: any) {
        super(props);
        const ds = new ListView.DataSource({
            rowHasChanged: (r1: any, r2: any) => r1 !== r2
        });
        this.state = {
            dataSource: ds,
            list: [],
            upLoading: false,
            pullLoading: false,
            height: document.documentElement!.clientHeight,
            page: 1,
            tab_status: '',
            empty: false,
            animating: true,
            pageCount: 10,
            tabs: [],
            defaultImg: 'https://www.e-health100.com/api/attachment/activityphoto/8336',
        };
    }
    componentDidMount() {
        let tabs: any = [
            { title: '资讯' },
        ];
        request(this, AppServiceUtility.person_org_manage_service.check_permission!({ 'method': 'release' }))
            .then((data: any) => {
                if (data) {
                    data['is_product'] && tabs.unshift({ title: '服务产品' });
                    data['is_activity'] && tabs.unshift({ title: '活动' });
                }
                this.setState(
                    {
                        tabs,
                        tab_status: tabs[0].title,
                    },
                    () => {
                        this.lc2();
                    }
                );
            }).catch(error => {
                this.setState(
                    {
                        tabs,
                        tab_status: tabs[0].title,
                    },
                    () => {
                        this.lc2();
                    }
                );
            });
    }
    lc2() {
        let { page, tab_status } = this.state;
        if (this.props.match!.params.key) {
            let paramKey = this.props.match!.params.key;
            this.setState(
                {
                    tab_status: paramKey,
                },
                () => {
                    this.getMyRelease(paramKey, page);
                }
            );
        } else {
            this.getMyRelease(tab_status, page);
        }
    }
    /** 明细点击事件 */
    on_click_detail = (type: string, owData: any) => {
        if (owData.status === '不通过') {
            alert('不通过原因', owData.sp_msg || '无', [
                { text: '确定', onPress: () => console.log('cancel') },
                {
                    text: '前往编辑', onPress: () => {
                        if (type === '活动') {
                            this.props.history!.push(ROUTE_PATH.activityDetail + '/' + owData.id + '/SH');
                        } else if (type === '资讯') {
                            this.props.history!.push(ROUTE_PATH.newsInfo + '/' + owData.id + '/SH');
                        }
                    }
                },
            ]);
            return;
        }
        if (type === '活动') {
            this.props.history!.push(ROUTE_PATH.activityDetail + '/' + owData.id + '/SH');
        } else if (type === '资讯') {
            this.props.history!.push(ROUTE_PATH.newsInfo + '/' + owData.id + '/SH');
        } else if (type === '服务产品') {
            this.props.history!.push(ROUTE_PATH.serviceDetails + '/' + owData.id);
        }
    }
    /** tab切换触发事件 */
    tab_click = (tab: any, index: number) => {
        this.setState(
            {
                list: [],
                empty: false,
                tab_status: tab.title,
            },
            () => {
                this.getMyRelease(tab.title, 1);
            }
        );
    }
    /** 下拉事件 */
    onEndReached = () => {
        let { page, tab_status } = this.state;
        this.getMyRelease(tab_status, page + 1);
    }
    getMyRelease(tab_status: any, page: number) {
        let { list, pageCount } = this.state;
        this.setState(
            {
                animating: true,
            },
            () => {
                if (tab_status === '活动') {
                    request(this, AppServiceUtility.activity_service.get_activity_list!({ all: 'all', page: page, 'user_id': '', 'is_mine': true }, page, pageCount))
                        .then((data: any) => {
                            if (data && data.result.length > 0) {
                                this.setState({
                                    list: list!.concat(data.result),
                                    page,
                                    animating: false,
                                });
                            } else {
                                this.setState({
                                    animating: false,
                                    empty: true,
                                });
                            }
                        });
                } else if (tab_status === '资讯') {
                    request(this, AppServiceUtility.article_list_service.get_news_list!({ all: 'all', page: page, 'user_id': '' }, page, pageCount))
                        .then((data: any) => {
                            if (data && data.result.length > 0) {
                                this.setState({
                                    list: list!.concat(data.result),
                                    page,
                                    animating: false,
                                });
                            } else {
                                this.setState({
                                    animating: false,
                                    empty: true,
                                });
                            }
                        });
                } else if (tab_status === '服务产品') {
                    request(this, AppServiceUtility.service_item_package.get_service_item_package!({ org_id: true }, page, pageCount))
                        .then((data: any) => {
                            if (data && data.result.length > 0) {
                                this.setState({
                                    list: list!.concat(data.result),
                                    page,
                                    animating: false,
                                });
                            } else {
                                this.setState({
                                    animating: false,
                                    empty: true,
                                });
                            }
                        });
                }
            }
        );
    }
    getShStatus(owData: any) {
        const spanWidth = 7;
        const style = {
            borderRadius: '5px',
            color: '#fff',
            padding: '2px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
        };
        if (!owData.hasOwnProperty('step_no')) {
            return (
                <Col span={spanWidth} style={{ background: "#5b9bd5", ...style }}>待审批</Col>
            );
        }
        if (owData.step_no === -1 || owData.step_no === '-1') {
            return (
                <Col span={spanWidth} style={{ background: "#70ad47", ...style }}>已通过</Col>
            );
        }
        if (owData.hasOwnProperty('status') && owData.status === '不通过') {
            return (
                <Col span={spanWidth} style={{ background: "#595959", ...style }}>不通过</Col>
            );
        }
        return (
            <Col span={spanWidth} style={{ background: "#5b9bd5", ...style }}>待审批</Col>
        );
    }
    render() {
        const { list, tabs, dataSource, empty, animating, tab_status, defaultImg } = this.state;
        // 获取item进行展示
        setMainFormTitle('发布');
        setMainFormBack('', () => {
            this.props.history!.push(ROUTE_PATH.mine);
        });
        const activityRow = (owData: any, sectionID: any, rowID: any) => {
            return (
                <Card className='list-conten' onClick={() => this.on_click_detail('activity', owData)}>
                    <Row type='flex' justify='center'>
                        <Col className='list-col' span={10}><img className="activity-img" src={owData.photo && owData.photo[0] ? owData.photo[0] : defaultImg} /></Col>
                        <Col span={14} className='list-col'>
                            <Row>
                                <Col span={17} className="happiness-info-row-title" style={{ WebkitBoxOrient: 'vertical' }}>{owData.activity_name}</Col>
                                {this.getShStatus(owData)}
                            </Row>
                            <Row className='list-row'>{owData.organization_name}</Row>
                            <Row>{getGoodLookTimeShow(owData.begin_date, owData.end_date)}</Row>
                            <Row>
                                <Col span={4} className="font-orange">{!owData.hasOwnProperty('amout') || owData.amount === 0 || owData.amount === '0' || owData === '' || owData.amount === undefined ? '免费' : `￥${owData['amount'] || 0}`}</Col>
                                <Col span={14}>已报名：{owData.participate_count || 0}/{owData.max_quantity}</Col>
                                <Col span={6}><Icon className='item-icon-size' type="star" />{owData.collection_count || 0}</Col>
                            </Row>
                        </Col>
                    </Row>
                </Card>
            );
        };
        const articleRow = (owData: any, sectionID: any, rowID: any) => {
            return (
                <Card className='list-conten'>
                    <Row type='flex' justify='center' onClick={() => this.on_click_detail('article', owData)}>
                        <Col className='list-col' span={10}><img src={owData.hasOwnProperty('app_img_list') && owData.app_img_list.length > 0 ? owData.app_img_list[0] : defaultImg} style={{ height: '72pt', width: '110pt' }} /></Col>
                        <Col span={14} className='list-col'>
                            <Row>
                                <Col span={17} className="happiness-info-row-title" style={{ WebkitBoxOrient: 'vertical' }}>{owData.title}</Col>
                                {this.getShStatus(owData)}
                            </Row>
                            <Row>作者：{owData['author'] || ''}</Row>
                            <Row className='list-t'>{moment(owData.create_date).format("YYYY-MM-DD hh:mm")}</Row>
                        </Col>
                    </Row>
                </Card>
            );
        };
        const productRow = (owData: any, sectionID: any, rowID: any) => {
            return (
                <Card className='list-conten'>
                    <Row type='flex' justify='center' onClick={() => this.on_click_detail('product', owData)}>
                        <Col className='list-col' span={10}><img className="activity-img" src={owData.picture_collection && owData.picture_collection[0] ? owData.picture_collection[0] : defaultImg} /></Col>
                        <Col span={14} className='list-col'>
                            <Row>产品名称：{owData.name}</Row>
                            <Row
                                className="maxLine5"
                                style={{
                                    WebkitBoxOrient: 'vertical',
                                }}
                            >
                                产品描述：{owData.introduce}
                            </Row>
                            <Row>{owData.org_info && owData.org_info.length > 0 && owData.org_info[0]['name'] ? owData.org_info[0]['name'] : ''}</Row>
                        </Col>
                    </Row>
                </Card>
            );
        };
        const emptyRow = (owData: any, sectionID: any, rowID: any) => {
            return (
                <div />
            );
        };
        // 获取默认页码
        let currentPage: number = 0;
        if (tabs && tabs.length > 0) {
            for (let i = 0; i < tabs.length; i++) {
                if (tabs[i] && tabs[i].title === tab_status) {
                    currentPage = i;
                }
            }
        }
        return (
            <Row>
                {tabs && tabs.length > 0 ? <Row>
                    <Tabs
                        tabs={tabs}
                        page={currentPage}
                        onTabClick={(tab, index) => this.tab_click(tab, index)}
                    />
                    <Row className='tabs-content'>
                        {
                            list && list.length ?
                                <ListView
                                    ref={el => this['lv'] = el}
                                    dataSource={dataSource.cloneWithRows(list)}
                                    renderRow={tab_status === '活动' ? activityRow : (tab_status === '服务产品' ? productRow : (tab_status === '资讯' ? articleRow : emptyRow))}
                                    initialListSize={10}
                                    pageSize={10}
                                    renderBodyComponent={() => <MyBody />}
                                    style={{ height: this.state.height }}
                                    onEndReached={this.onEndReached}
                                /> : null
                        }
                    </Row>
                </Row> : null}
                {animating ? <Row>
                    <WhiteSpace size="lg" />
                    <Row style={{ textAlign: 'center' }}>
                        <Spin size="large" />
                    </Row>
                    <WhiteSpace size="lg" />
                </Row> : null}
                {empty ? <Row>
                    <WhiteSpace size="lg" />
                    <Row className='tabs-content' type='flex' justify='center'>{list && list.length ? '已经是最后一条了' : '无数据'}</Row>
                    <WhiteSpace size="lg" />
                </Row> : null}
            </Row>
        );
    }
}

/**
 * 组件：我的发布列表视图控件
 * 控制我的发布列表视图控件
 */
@addon('MyReleaseView', '我的发布列表视图控件', '控制我的发布列表视图控件')
@reactControl(MyReleaseView, true)
export class MyReleaseViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}